package com.stock.stockana.requests;

import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.android.volley.AuthFailureError;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.stock.publiclib.utils.StringUtil;
import com.stock.stockana.beans.ResponseBean;
import com.stock.stockana.constants.NetWorkConstants;
import com.stock.stockana.events.network.LoginInEvent;
import com.stock.stockana.events.network.SignUpEvent;

import java.util.HashMap;
import java.util.Map;

import de.greenrobot.event.EventBus;

/**
 * Created by ljgsonx on 2016/1/24.
 */
public class SignUp extends BaseStringRequest<SignUp> {

    private final static String TAG = "SignUp--->";
    private String passwd;
    private String mobilephone;
    private String email;

    private SignUp() {
        super(Method.POST, NetWorkConstants.SIGNUP_URL, listener, errorListener);
        Log.d(TAG, NetWorkConstants.SIGNUP_URL);
    }

    static Response.Listener<String> listener = new Response.Listener<String>(){

        @Override
        public void onResponse(String response) {
            try{
                ResponseBean rb = JSON.parseObject(response, ResponseBean.class);
                EventBus.getDefault().post(new SignUpEvent(rb));
            }catch (Exception e) {
                ResponseBean rb = new ResponseBean();
                rb.setRespCode(NetWorkConstants.RESPONSE_CODE_ERROR);
                rb.setErrorMsg(NetWorkConstants.RESPONSE_ERROR1 + response);
                EventBus.getDefault().post(new SignUpEvent(rb));
            }
        }
    };

    static Response.ErrorListener errorListener = new Response.ErrorListener(){

        @Override
        public void onErrorResponse(VolleyError error) {
            ResponseBean rb = new ResponseBean();
            rb.setRespCode(NetWorkConstants.RESPONSE_CODE_SERVER_ERROR);
            rb.setErrorMsg(NetWorkConstants.RESPONSE_ERROR3 + error.toString());
            EventBus.getDefault().post(new SignUpEvent(rb));
        }
    };

    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        Map<String, String> map = new HashMap<>();
        if (!StringUtil.hasBlank(mobilephone, passwd)) {
            map.put("mobilephone", mobilephone);
            map.put("passwd", passwd);
        }else if(!StringUtil.hasBlank(email, passwd)){
            map.put("email", email);
            map.put("passwd", passwd);
        }
        return map;
    }

    public static SignUp build() {
        return new SignUp();
    }

    public SignUp setEmailAndPwd(String email, String userPwd) {
        this.email = email;
        this.passwd = userPwd;
        return this;
    }

    public SignUp setPhoneNumAndPwd(String phoneNum, String userPwd) {
        this.mobilephone = phoneNum;
        this.passwd = userPwd;
        return this;
    }
}
